package com.hunktimes.wholesale.extension

import android.os.Bundle
import androidx.annotation.IdRes
import androidx.annotation.NonNull
import androidx.navigation.NavController
import androidx.navigation.NavController.OnDestinationChangedListener
import androidx.navigation.NavDestination
import androidx.navigation.ui.NavigationUI
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.hunktimes.wholesale.util.L
import com.hunktimes.wholesale.util.SP
import java.lang.ref.WeakReference

/**
 * Author: Delete
 * Date: 2020/8/4 10:11
 * Description:
 *
 */

/**
 * @param filterTabIds 需要进行登录拦截的 tab id
 */
fun BottomNavigationView.setupWithNavControllerV2(
    navController: NavController,
    vararg filterTabIds: Int,
    loginInterceptor: () -> Unit
) {
    setupWithNavController(this, navController, filterTabIds, loginInterceptor)
}


fun setupWithNavController(
    bottomNavigationView: BottomNavigationView,
    navController: NavController,
    tabIds: IntArray,
    loginInterceptor: () -> Unit
) {
    bottomNavigationView.setOnNavigationItemSelectedListener { item ->
        if (tabIds.isNotEmpty() && tabIds.contains(item.itemId)) {
            L.d("没登录,要拦截tab点击,跳转登录")
            loginInterceptor.invoke()
            false
        } else {
            NavigationUI.onNavDestinationSelected(
                item,
                navController
            )
        }
    }
    val weakReference =
        WeakReference(bottomNavigationView)
    navController.addOnDestinationChangedListener(
        object : OnDestinationChangedListener {
            override fun onDestinationChanged(
                controller: NavController,
                destination: NavDestination, arguments: Bundle?
            ) {
                val view = weakReference.get()
                if (view == null) {
                    navController.removeOnDestinationChangedListener(this)
                    return
                }
                val menu = view.menu
                var h = 0
                val size = menu.size()
                while (h < size) {
                    val item = menu.getItem(h)
                    if (matchDestination(destination, item.itemId)) {
                        item.isChecked = true
                    }
                    h++
                }
            }
        })
}

fun matchDestination(
    @NonNull destination: NavDestination,
    @IdRes destId: Int
): Boolean {
    var currentDestination: NavDestination? = destination
    while (currentDestination!!.id != destId && currentDestination.parent != null) {
        currentDestination = currentDestination.parent
    }
    return currentDestination.id == destId
}
